import json
import random

import pandas

from base.base import Base
from dao.mysqlhelper import MySQLHelper
from utils.config import Config


def get_token():
    url = f'http://{base_url}/idaas/idaas-gateway/wutong-idaas-auth/login'
    headers = {
        'content-type': 'application/json',
        'tenantid': 'defaultTenantId'
    }
    data = {
        "password": "ff960e9eeeff3b417fbf44bdc8f8d8c1",
        "username": "zzh",
        "captchaCode": "11",
        "captchaKey": "d1a780db-cdce-4900-886d-dbbbb68f743b"
    }
    try:
        res = json.loads(base.send_post(url, param_type, headers=headers, data=data))
        return res['data']['Authorization']
    except Exception as e:
        print(f"获取 Token 失败: {e}")
        return None


# 查属性信息
def get_attribute(categoryId,token):
    url = f'http://{base_url}/gateway/code-one/entityModelDetail/filterAttributeDict'
    headers = {
        'content-type': 'application/json',
        'authorization': token
    }
    data = {
        "categoryId": categoryId
    }
    try:
        res = json.loads(base.send_post(url, param_type, headers=headers, data=data))
        return res['data'] if 'data' in res and res['data'] else {}
    except Exception as e:
        print(f"获取属性失败: {e}")
        return {}


# 获取分类id
def get_category_id(row):
    key = row[0]
    sql = f"select category_id from entity_category where namepath='{key}'"
    res = mysql.select(sql)
    if res :
        return res[0][0]
    else:
        return None


# 保存模型属性
def saveAttribute(categoryId, parameter):
    url = f'http://{base_url}/gateway/code-one/entityModelDetail/saveAttribute'
    headers = {
        'content-type': 'application/json',
        'authorization': get_token()
    }
    data = {
        "categoryId": categoryId,
        "list": parameter,
        "version": "1"
    }
    try:
        res = json.loads(base.send_post(url, param_type, headers=headers, data=data))
        return res
    except Exception as e:
        print(f"保存属性失败: {e}")
        return {}

file_path = 'D:\\IOT3.0\\2024.09\\实体赋码平台\\标准分类&属性&模型导信息_1026.xlsx'
df = pandas.read_excel(file_path, header=None, engine='openpyxl', sheet_name='标准模型', skiprows=1)

data_dict = {}
base = Base()
param_type = 'application/json'
mysql = MySQLHelper()
config=Config('../conf/config.ini')
base_url=config.read_value('system','base_url')
token=get_token()
for index, row in df.iterrows():
    ''' 对每一行进行迭代，获取 category_id。
        如果 category_id 为空，则跳过当前行。
        提取并过滤有效的 configName。
        如果没有有效的 configName（即 result 为空），则打印提示并跳过后续处理。
        如果有有效的 configName，则生成参数并调用保存函数。'''
    category_id = get_category_id(row)
    if category_id is None:
        print(f"{row[0]}，分类id未找到。")
        continue  # 如果获取 category_id 失败，则跳过此行

    values = set(row[1:].dropna().tolist())
    res = get_attribute(category_id,token)
    # 过滤出 attributeId 为 values列表内 的数据
    result = [item for item in res if item["configName"] in values]

    # 如果 result 为空，跳过后续处理
    if not result:
        print(f"{row[0]}，分类id为：{category_id}，无有效入参，跳过该行。")
        continue  # 直接跳过后续处理

    parameter = []
    if result:  # 仅在 result 有效时处理
        for item in result:
            random_8_digit_integer = random.randint(10000000, 99999999)
            item['isMust'] = 'false'
            item['key'] = f"47666fc3e4ab473195374d47{random_8_digit_integer}"
            parameter.append(item)
    res=saveAttribute(category_id,parameter)
    print(f"{row[0]}，结果为{res}  分类id为：{category_id}，入参为：{parameter}")
